import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import pool from '@/utils/db';

// 更新技能
export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    const skillId = parseInt(params.id);

    if (isNaN(skillId)) {
      return NextResponse.json(
        { error: '无效的技能ID' },
        { status: 400 }
      );
    }

    const { name, proficiency, description } = await request.json();

    // 验证输入
    if (!name || name.trim() === '') {
      return NextResponse.json(
        { error: '技能名称不能为空' },
        { status: 400 }
      );
    }

    // 检查proficiency是否在有效范围内(1-3)
    const proficiencyNum = Number(proficiency);
    if (isNaN(proficiencyNum) || proficiencyNum < 1 || proficiencyNum > 3) {
      return NextResponse.json(
        { error: '熟练度必须在1到3之间' },
        { status: 400 }
      );
    }

    // 验证技能是否属于当前用户
    const [existingSkill] = await pool.query(
      'SELECT * FROM skills WHERE id = ? AND user_id = ?',
      [skillId, userId]
    );

    if ((existingSkill as any[]).length === 0) {
      return NextResponse.json(
        { error: '技能不存在或无权操作' },
        { status: 404 }
      );
    }

    // 检查是否与其他技能名称冲突
    const [duplicateSkill] = await pool.query(
      'SELECT * FROM skills WHERE name = ? AND user_id = ? AND id != ?',
      [name, userId, skillId]
    );

    if ((duplicateSkill as any[]).length > 0) {
      return NextResponse.json(
        { error: '已存在相同名称的技能' },
        { status: 400 }
      );
    }

    // 更新技能
    await pool.query(
      'UPDATE skills SET name = ?, proficiency = ?, description = ?, updated_at = NOW() WHERE id = ? AND user_id = ?',
      [name, proficiencyNum, description || '', skillId, userId]
    );

    // 查询更新后的技能
    const [updatedSkill] = await pool.query(
      'SELECT * FROM skills WHERE id = ?',
      [skillId]
    );

    return NextResponse.json({
      success: true,
      skill: (updatedSkill as any[])[0],
      message: '技能更新成功'
    });
  } catch (error) {
    console.error('更新技能失败:', error);
    return NextResponse.json(
      { error: '更新技能失败' },
      { status: 500 }
    );
  }
}

// 删除技能
export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    const skillId = parseInt(params.id);

    if (isNaN(skillId)) {
      return NextResponse.json(
        { error: '无效的技能ID' },
        { status: 400 }
      );
    }

    // 验证技能是否属于当前用户
    const [existingSkill] = await pool.query(
      'SELECT * FROM skills WHERE id = ? AND user_id = ?',
      [skillId, userId]
    );

    if ((existingSkill as any[]).length === 0) {
      return NextResponse.json(
        { error: '技能不存在或无权操作' },
        { status: 404 }
      );
    }

    // 删除技能
    await pool.query(
      'DELETE FROM skills WHERE id = ? AND user_id = ?',
      [skillId, userId]
    );

    return NextResponse.json({
      success: true,
      message: '技能删除成功'
    });
  } catch (error) {
    console.error('删除技能失败:', error);
    return NextResponse.json(
      { error: '删除技能失败' },
      { status: 500 }
    );
  }
} 